package com.zuo.demo01.service.impl;

import com.zuo.demo01.config.Constants;
import com.zuo.demo01.dao.BlogMapper;
import com.zuo.demo01.dao.BlogTagRelationMapper;
import com.zuo.demo01.dao.TagMapper;
import com.zuo.demo01.pojo.Blog;
import com.zuo.demo01.pojo.BlogTagRelation;
import com.zuo.demo01.pojo.Tag;
import com.zuo.demo01.service.BlogService;
import com.zuo.demo01.utils.MarkDownUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private BlogTagRelationMapper blogTagRelationMapper;

    @Override
    public List<Blog> findAll(Map<String, Object> map) {
        return blogMapper.findAll(map);
    }

    @Override
    public List<Blog> findAllPub(Map<String, Object> map) {
        return blogMapper.findAllPub(map);
    }

    @Override
    public List<Blog> findByKey(Map<String, Object> map) {
        return blogMapper.findByKey(map);
    }

    @Override
    public List<Blog> findByType(int type,int limit) {
        Map<String,Object> map = new HashMap<>();
        map.put("type",type);
        map.put("limit",limit);
        return blogMapper.findByType(map);
    }

    @Override
    public List<Blog> findByCategory(Map<String, Object> map) {
        return blogMapper.findByCategory(map);
    }

    @Override
    public List<Blog> findByTag(Map<String,Object> map) {

        List<Blog> blogs = new ArrayList<>();
        for (BlogTagRelation btr :
                blogTagRelationMapper.findByTag(map)) {
            blogs.add(btr.getBlog());
        }
        return blogs;
    }

    @Override
    public List<Blog> getAll() {
        return blogMapper.getAll();
    }

    @Override
    public Blog getById(int id) {
        return blogMapper.getById(id);
    }

    @Override
    public Blog getByIdInHTML(int id) {
        Blog blog = blogMapper.getById(id);
        blog.setContent(MarkDownUtil.mdToHtml(blog.getContent()));
        return blog;
    }

    @Override
    public int count() {
        return blogMapper.count();
    }

    @Override
    public int countByPub() {
        return blogMapper.countByPub();
    }

    @Override
    public int countByKey(String key) {
        return blogMapper.countByKey(key);
    }

    @Override
    public int countByCategory(String categoryName) {
        return blogMapper.countByCategory(categoryName);
    }

    @Override
    public int countByTag(String tag) {
        return blogTagRelationMapper.countByTag(tag);
    }

    @Override
    public String insert(Map<String, Object> map) {

        Date date = new Date(System.currentTimeMillis());

        String tags[] = map.get("tags").toString().split(",");

        List<Integer> tagsId = new ArrayList<>();//为了添加关系表，存tagId
        for (String tag : //未有的标签存入数据库
                tags) {
            Tag tag1 = tagMapper.selectByName(tag); //搜寻标签名相同的
            if(tag1==null){//没有标签名相同的就添加
                Tag tag_insert = new Tag();
                tag_insert.setName(tag);
                tag_insert.setCreateTime(date);
                if(tagMapper.insert(tag_insert) == 0){//添加tag，会返回自增id
                    return "标签插入error";
                }
                tagsId.add(tag_insert.getId());//存tag未存在的
            }else{
                tagsId.add(tag1.getId());//存tag存在的
            }
        }

        map.put("createTime",date);
        if(blogMapper.insert(map)==1){//添加blog，会返回自增id
            //博客和标签的关系表添加
            Map<String,Object> map1 = new HashMap<>();
            map1.put("blogId",map.get("id"));
            map1.put("createTime",date);
            for (Integer tagId :
                    tagsId) {
                map1.put("tagId", tagId); //逐个tags和blog的关系添加
                if(blogTagRelationMapper.insert(map1)==0){
                    return "博客和标签关系表添加error";
                }
            }
            return "success";
        }

        return "error";
    }

    @Override
    public String update(Map<String, Object> map) {
        Date date = new Date(System.currentTimeMillis());

        String tags[] = map.get("tags").toString().split(",");

        List<Integer> tagsId = new ArrayList<>();//为了添加关系表，存tagId
        for (String tag : //未有的标签存入数据库
                tags) {
            Tag tag1 = tagMapper.selectByName(tag); //搜寻标签名相同的
            if(tag1==null){//没有标签名相同的就添加
                Tag tag_insert = new Tag();
                tag_insert.setName(tag);
                tag_insert.setCreateTime(date);
                if(tagMapper.insert(tag_insert) == 0){//添加tag，会返回自增id
                    return "标签插入error";
                }
                tagsId.add(tag_insert.getId());//存tag未存在的
            }
        }

        map.put("updateTime",date);
        int result= blogMapper.update(map);
        if(result==1){//修改blog，会返回自增id
            //博客和标签的关系表添加
            Map<String,Object> map1 = new HashMap<>();
            map1.put("blogId",map.get("id")); // 这个id是修改后返回回来的
            map1.put("createTime",date);
            for (Integer tagId :
                    tagsId) {
                map1.put("tagId", tagId); //逐个tags和blog的关系添加
                if(blogTagRelationMapper.insert(map1)==0){
                    return "博客和标签关系表添加error";
                }
            }
            return "success";
        }

        return "error";

    }

    @Override
    public int addViews(int id) {
        Map<String,Object> map = new HashMap<>();
        Blog blog = blogMapper.getById(id);

        map.put("views",blog.getViews()+1);
        map.put("id",id);
        return blogMapper.addViews(map);
    }

    @Override
    public int delete(int id) {
        Blog blog = this.getById(id);
        int result = blogMapper.delete(id);
        if(result == 0){
            return result;
        }

        //删除博客封面
        File file = new File(Constants.FILE_IMGS_BLOGS_HEADER);
        for (File del_file :
                file.listFiles()) {
            if(del_file.getName().length()>7&&del_file.getName().equals(blog.getImage())){
                del_file.delete();
                break;
            }
        }

        //删除博客内容图片
        File contents = new File(Constants.FILE_IMGS_BLOGS_CONTENT);
        for (File content:
             contents.listFiles()) {
            if(content.getName().equals(blog.getUrl())){
                for(File cont:content.listFiles()){
                    cont.delete();
                }
                content.delete();
                break;
            }
        }
        return result;
    }
}
